<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * YekComputer (r) CMS controller class
 * 
 * @version: 1.0
 * @copyright (c) 2009, YekComputer. All rights reserved.
 * @author Babak Taraghi 'babak.taraghi@gmail.com'
 * @license Code licensed under the BSD License.
 */
class Categories extends CI_Controller {

	/**
	 * @desc Array - datas which should pass to the views
	 */
	var $data = array();
	
	
	/**
	 * @desc String - html of the created categories tree will append to this property
	 */
	var $treeHTML;
	
	
	/**
	 * @desc String - related model class name to this controller
	 */
	var $modelName = "categoriesModel";
	
	
	
	/**
	 * Controller constructor
	 * 
	 * @desc This will check the session to see if the user is logged in or not
	 * And will load the related language files
	 * And will set title,breadcrumb and activeMenu for this controller in $this->data
	 */
	function Categories(){
		parent::__construct();
		if(!$this->session->userdata('cploggedin')){
			redirect("cp/users");
		}
		
		$this->lang->load("cp");
		$this->lang->load("categories");
		
		$this->data["title"] = $this->lang->line("cpTitle");
		$this->data["title"] .= " - ".$this->lang->line("categories");
		$this->data["breadcrumb"] = array($this->lang->line("home")=>base_url()."cp");
		
		$this->load->model($this->modelName);
		$this->load->model("accessLevelModel");
		
		$this->data["contactsModuleAL"] = $this->accessLevelModel->getRecords(array("module_name"=>"contactsModule","category_id"=>$this->session->userdata["category_id"]));
		$this->data["newsModuleAL"] = $this->accessLevelModel->getRecords(array("module_name"=>"newsModule","category_id"=>$this->session->userdata["category_id"]));
		$this->data["cpusersModuleAL"] = $this->accessLevelModel->getRecords(array("module_name"=>"cpusersModule","category_id"=>$this->session->userdata["category_id"]));
		$this->data["pagesModuleAL"] = $this->accessLevelModel->getRecords(array("module_name"=>"pagesModule","category_id"=>$this->session->userdata["category_id"]));
		$this->data["productsModuleAL"] = $this->accessLevelModel->getRecords(array("module_name"=>"productsModule","category_id"=>$this->session->userdata["category_id"]));
		
	}
	

	/**
	 * @desc This will show the tree of categories started from $moduleName node
	 * @param String 'moduleName' this is the internal_name value also mentioned as module name in controllers
	 */
	function getCatsHTML($modelName){
		
		$this->data["currentModelName"] = $modelName;
		$this->load->model($modelName);
		$moduleName = $this->$modelName->moduleName;
		$this->lang->load($moduleName);
		
		$this->data["categoryScript"] = true;
		
		if(!isset($this->$modelName->listControllerName))
			$this->$modelName->listControllerName = "home";
		
		$this->data["breadcrumb"][$this->lang->line($moduleName)] = base_url()."cp/".$this->$modelName->listControllerName."/inventory/".$moduleName."Model";
		$this->data["moduleName"] = $moduleName;
		
		$accessLevelRecs = $this->accessLevelModel->getRecords(array("module_name"=>$this->$modelName->moduleName."Module","category_id"=>$this->session->userdata["category_id"]));
		
		if(count($accessLevelRecs) > 0)$accessLevel = $accessLevelRecs[0];
		else $accessLevel = null;
		
		if(count($accessLevelRecs) < 1 || !$accessLevel->perm_view){
			
			$this->data["errors"][] = $this->lang->line("no-perm");
			$this->data["content"] = $this->load->view("cp/messages",$this->data,TRUE);
		
		}else{
		
			$this->data["modelName"] = $modelName;
			$this->data["lang"] = "en";
			$this->data["breadcrumb"][$this->lang->line("categories")] = "";
			
			$categoriesModelName = $this->modelName;
			$moduleCatRecord = $this->$categoriesModelName->getRecordByInternalName($moduleName);
			
			$this->data["treeHTML"] = $this->getTreeHTML($moduleCatRecord,$modelName);
			
			$this->data["content"] = $this->load->view("cp/categories",$this->data,TRUE);
		}
		
		// check to see if the request is ajax based or not
		if($this->input->is_ajax_request()){
			
			$i=0;
			$breadCrumb = "";
			foreach($this->data["breadcrumb"] as $bread=>$crumb){
				if(++$i > 1) $breadCrumb .= "&nbsp;&raquo;&nbsp;";
				if($crumb != ""){
					$breadCrumb .= "<a href=".$crumb." onclick=\"one.changeContent(this.href); return false;\">";
				}
				$breadCrumb .= $bread;
				if($crumb != ""){
					$breadCrumb .= "</a>";
				}
			}
			$json = "{";
			$json .= "breadCrumb:'".$breadCrumb."',";
			$json .= "title:'".$this->data["title"]."',";
			$json .= "categoriesScript:'1'";
			$json .= "}";
			echo $json."|-|".$this->data["content"];
		}else{
			$this->load->view('cp/container',$this->data);
		}
		
	}
	
	
	
	/**
	 * @desc This will get called by ajax api when user needs to see cats tree in another lang
	 * @param $modelName
	 * @param $lang
	 */
	function getCatsHTMLForLang($modelName,$lang){
		$this->data["currentModelName"] = $modelName;
		
		$this->load->model($modelName);
		$moduleName = $this->$modelName->moduleName;
		$this->lang->load($moduleName);
		
		if(!isset($this->$modelName->listControllerName))
			$this->$modelName->listControllerName = "home";
		
		$this->data["breadcrumb"][$this->lang->line($moduleName)] = base_url()."cp/".$this->$modelName->listControllerName."/inventory/".$moduleName."Model";
		$this->data["moduleName"] = $moduleName;
		$this->data["modelName"] = $modelName;
		$this->data["breadcrumb"][$this->lang->line("categories")] = "";
		
		$categoriesModelName = $this->modelName;
		$moduleCatRecord = $this->$categoriesModelName->getRecordByInternalName($moduleName);
		
		$this->data["treeHTML"] = $this->getTreeHTML($moduleCatRecord,$modelName,$lang);
		
		$this->data["lang"] = $lang;
		
		$this->data["content"] = $this->load->view("cp/categories",$this->data,true);
		
		
		
		// check to see if the request is ajax based or not
		if($this->input->is_ajax_request()){
			$i=0;
			$breadCrumb = "";
			foreach($this->data["breadcrumb"] as $bread=>$crumb){
				if(++$i > 1) $breadCrumb .= "&nbsp;&raquo;&nbsp;";
				if($crumb != ""){
					$breadCrumb .= "<a href=".$crumb." onclick=\"one.changeContent(this.href); return false;\">";
				}
				$breadCrumb .= $bread;
				if($crumb != ""){
					$breadCrumb .= "</a>";
				}
			}
			$json = "{";
			$json .= "breadCrumb:'".$breadCrumb."',";
			$json .= "title:'".$this->data["title"]."',";
			$json .= "categoriesScript:'1'";
			$json .= "}";
			echo $json."|-|".$this->data["content"];
		}else{
			$this->load->view('cp/container',$this->data);
		}
		
		
	}
	
	
	
	
	/**
	 * 
	 * @param Object 'parentRecord' parent record main node, Tree will start from this node
	 * @return String 'treeHTML' - containes html of body tree
	 */
	function getTreeHTML($parentRecord,$modelName,$lang="en"){
		
		if($parentRecord->children > 0){
			$this->treeHTML = "<a class='treeUl' style='background-image : url(\"".base_url()."files/cp/icons/minus.gif\");' onclick='showHideChildren(this,$parentRecord->id)'>";
		}else{
			$this->treeHTML = "<a>";
		}
		
		$categoriesModelName = $this->modelName;
		$langRecord = $this->$categoriesModelName->getLangRecord($parentRecord->id,$lang);
		
		$this->treeHTML .= "<span id='title-$parentRecord->id'>";
		$this->treeHTML .= (is_object($langRecord))?$langRecord->title:"";
		$this->treeHTML .= "</span></a>";
//		$this->treeHTML .= "&nbsp;&nbsp;&nbsp;<a title='Rename Category' onclick='editCat($parentRecord->id)'><img src='".base_url()."files/cp/icons/edit.gif' border='0'></a>";
		$this->treeHTML .= "&nbsp;&nbsp;&nbsp;<a title='Add Sub Category' onclick='addSubCat($parentRecord->id,\"$modelName\")'><img src='".base_url()."files/cp/icons/add.gif' border='0'></a>";
//		$this->treeHTML .= "<a title='Remove Category' onclick='removeCat($parentRecord->id)'><img src='".base_url()."files/cp/icons/delete.gif' border='0'></a>";
		if($parentRecord->children > 0){
			$this->printChildren($parentRecord->id,$lang);
		}else{
			$this->treeHTML .= "<ul id='children-$parentRecord->id'></ul>"; // will be use if user dynamicly add child
		}
		return $this->treeHTML;
	}
    
	
	
	/**
	 * @desc this will append children html of the parent node to treeHTML
	 * @param Integer 'parentId' id of the parent node for these children
	 */
	function printChildren($parentId,$lang){
		$this->treeHTML .= "<ul id='children-$parentId'>";
		$modelName = $this->modelName;
		$records = $this->$modelName->getChildren($parentId);
		
		foreach($records as $record){
			if($record->children > 0){
				$this->treeHTML .= "<li class='treeLi' id='container-$record->id'><a class='treeUl' style='background-image : url(\"".base_url()."files/cp/icons/minus.gif\");' onclick='showHideChildren(this,$record->id)'>";
			}else{
				$this->treeHTML .= "<li class='treeLi' id='container-$record->id'><a>";
			}
			
			$langRecord = $this->$modelName->getLangRecord($record->id,$lang);
			
			$this->treeHTML .= "<span id='title-$record->id'>";
			if($record->internal_name != ""){
				$this->treeHTML .= " <span style='color:red;'>*</span> ";
				
			}
			$this->treeHTML .= (is_object($langRecord))?$langRecord->title:"";
			$this->treeHTML .= "</span></a>";
			$this->treeHTML .= "&nbsp;&nbsp;&nbsp;<a title='Rename Category' onclick='editCat($record->id)'><img src='".base_url()."files/cp/icons/edit.gif' border='0'></a>";
			$this->treeHTML .= "<a title='Add Sub Category' onclick='addSubCat($record->id,\"".$this->data["currentModelName"]."\")'><img src='".base_url()."files/cp/icons/add.gif' border='0'></a>";
			$this->treeHTML .= "<a title='Remove Category' onclick='removeCat($record->id)'><img src='".base_url()."files/cp/icons/delete.gif' border='0'></a>";
			$this->treeHTML .= "<a title='Move Category Up' onclick='moveCat(\"up\",$record->id,\"".$this->data["currentModelName"]."\")'><img src='".base_url()."files/cp/icons/up.gif' border='0'></a>";
			$this->treeHTML .= "<a title='Move Category Down' onclick='moveCat(\"down\",$record->id,\"".$this->data["currentModelName"]."\")'><img src='".base_url()."files/cp/icons/down.gif' border='0'></a>";
			$this->treeHTML .= "</li>";
			if($record->children > 0)
				$this->printChildren($record->id,$lang);
		}
		$this->treeHTML .= "</ul>";
	}
	
	
	
	

	/**
	 * @desc This is for ajax calls in tree of categories and will set a new name for category
	 * @param Integer $_POST 'catId' id of the category which needed to rename
	 * @param String $_POST 'newName' new name of the category
	 */
	function setCatName($catId,$newName,$lang){
		
		$modelName = $this->modelName;
		$moduleName = "";
		
		$id = $catId;
		while($moduleName == "" || $rec->parent_id != "1"){
			$rec = $this->$modelName->getRecord($id);
			$id = $rec->parent_id;
			$moduleName = $rec->internal_name;
		}
		
		$accessLevelRecs = $this->accessLevelModel->getRecords(array("module_name"=>$moduleName."Module","category_id"=>$this->session->userdata["category_id"]));
		
		if(count($accessLevelRecs) > 0)$accessLevel = $accessLevelRecs[0];
		else $accessLevel = null;
		
		if(count($accessLevelRecs) < 1 || !$accessLevel->perm_edit){
			
			echo "0-".$this->lang->line("no-perm");
		
		}else{
			
			$fieldsValues = array(
				"title"=>urldecode($newName)
			);
			
			$record = $this->$modelName->getLangRecord($catId,$lang);
			if(is_object($record)){
				if($this->$modelName->updateLang($catId,$lang,$fieldsValues)){
					echo "1-".$this->lang->line("edited");
				}else{
					echo "0-".$this->lang->line("notEdited");
				}
			}else{
				$fieldsValues["cat_id"] = $catId;
				$fieldsValues["language"] = $lang;
				if($this->$modelName->insertLang($fieldsValues)){
					echo "1-".$this->lang->line("edited");
				}else{
					echo "0-".$this->lang->line("notEdited");
				}
			}
		}
	}
	
	
	
	
	/**
	 * @desc This is for ajax calls in tree of categories and will insert a new sub category
	 * @param Integer $_POST 'catId' id of the category which needed a new sub category
	 * @param String $_POST 'newName' name of the new sub category
	 */
	function addSubCat($parentId,$newName,$lang){
		
		$modelName = $this->modelName;
		$moduleName = "";
		
		$id = $parentId;
		while($moduleName == "" || $rec->parent_id != "1"){
			$rec = $this->$modelName->getRecord($id);
			$id = $rec->parent_id;
			$moduleName = $rec->internal_name;
		}
		
		$accessLevelRecs = $this->accessLevelModel->getRecords(array("module_name"=>$moduleName."Module","category_id"=>$this->session->userdata["category_id"]));
		
		if(count($accessLevelRecs) > 0)$accessLevel = $accessLevelRecs[0];
		else $accessLevel = null;
		
		if(count($accessLevelRecs) < 1 || !$accessLevel->perm_add){
			
			echo "0-".$this->lang->line("no-perm");
		
		}else{
			
			$children = $this->$modelName->getChildren($parentId);
			
			$lastChildOrder = 0;
			foreach ($children as $child){
				if($child->order > $lastChildOrder){
					$lastChildOrder = $child->order;
				}
			}
			
			$fieldsValues = array(
				"parent_id"=>$parentId,
				"order"=>intval($lastChildOrder)+1
			);
			if($this->$modelName->insert($parentId,$fieldsValues)){
				$catId = $this->db->insert_id();
				$langsFieldsValues = array(
					"title"=>urldecode($newName),
					"language"=>$lang,
					"cat_id"=>$catId
				);
				$this->$modelName->insertLang($langsFieldsValues);
				echo $catId."-".$this->lang->line("inserted");
			}else{
				echo "0-".$this->lang->line("notInserted");
			}
		}
	}
	
	
	
	
	/**
	 * @desc This is for ajax calls in tree of categories and will remove a category if the category has no child or internal name
	 * @param Integer $_POST 'catId' id of the category which have to delete
	 */
	function removeCat($catId){
		
		$modelName = $this->modelName;
		$moduleName = "";
		
		$id = $catId;
		while($moduleName == "" || $rec->parent_id != "1"){
			$rec = $this->$modelName->getRecord($id);
			$id = $rec->parent_id;
			$moduleName = $rec->internal_name;
		}
		
		$accessLevelRecs = $this->accessLevelModel->getRecords(array("module_name"=>$moduleName."Module","category_id"=>$this->session->userdata["category_id"]));
		
		if(count($accessLevelRecs) > 0)$accessLevel = $accessLevelRecs[0];
		else $accessLevel = null;
		
		if(count($accessLevelRecs) < 1 || !$accessLevel->perm_delete){
			
			echo "0-".$this->lang->line("no-perm");
		
		}else{
			
			$cat = $this->$modelName->getRecord($catId);
			if($cat->internal_name == ""){
				$children = $this->$modelName->getChildren($catId);
				if(count($children) > 0){
					echo "0-".$this->lang->line("hasChildren");
				}elseif($this->$modelName->delete($catId)){
					$this->$modelName->deleteLang($catId);
					echo "1-".$this->lang->line("catDeleted");
				}else{
					echo "0-".$this->lang->line("catCanntDelete");
				}
			}else{
				echo "0-".$this->lang->line("internalCatDelete");
			}
		}
	}
	
	
	
	
	function moveCatUp($requestedModelName,$catId,$lang){
		
		$modelName = $this->modelName;
		$moduleName = "";
		
		$id = $catId;
		while($moduleName == "" || $rec->parent_id != "1"){
			$rec = $this->$modelName->getRecord($id);
			$id = $rec->parent_id;
			$moduleName = $rec->internal_name;
		}
		$accessLevelRecs = $this->accessLevelModel->getRecords(array("module_name"=>$moduleName."Module","category_id"=>$this->session->userdata["category_id"]));
		
		if(count($accessLevelRecs) > 0)$accessLevel = $accessLevelRecs[0];
		else $accessLevel = null;
		
		if(count($accessLevelRecs) < 1 || !$accessLevel->perm_edit){
			
			echo "0-|-".$this->lang->line("no-perm");
		
		}else{
			
			$record = $this->$modelName->getRecord($catId);
			if(is_object($record)){
				
				$order = $record->order;
				
				if($order > 0){
					if($order == 1){
						echo "0-|-".$this->lang->line("alreadyTop");
						
					}else{
						
						$where = array(
							"parent_id"=>$record->parent_id,
							"order"=>$order-1
						);
						$topRecords = $this->$modelName->getRecords($where);
						$topRecord = $topRecords[0];
						
						$this->$modelName->update($topRecord->id,array("order"=>(intval($topRecord->order)+1)));
						$this->$modelName->update($record->id,array("order"=>(intval($record->order)-1)));
						
						@ob_start();
						$this->getCatsHTMLForLang($requestedModelName,$lang);
						$content = ob_get_clean();
						
						echo "1-|-".$this->lang->line("moved")."-|-".$content;
					}
					
				}elseif($order == 0){
					$where = array(
						"parent_id"=>$record->parent_id
					);
					$lastRecords = $this->$modelName->getRecords($where);
					foreach($lastRecords as $lastRecord){
						if($lastRecord->order > 0) $newOrder = intval($lastRecord->order) + 1;
					}
					if(!isset($newOrder)) $newOrder = 1;
					
					$this->$modelName->update($record->id,array("order"=>$newOrder));
					
					@ob_start();
					$this->getCatsHTMLForLang($requestedModelName,$lang);
					$content = ob_get_clean();
					
					echo "1-|-".$this->lang->line("moved")."-|-".$content;
				}
				
				
			}else{
				echo "0-|-".$this->lang->line("notEdited");
			}
		}
	}
	
	
	
	
	
	
	
	function moveCatDown($requestedModelName,$catId,$lang){
		
		$modelName = $this->modelName;
		$moduleName = "";
		
		$id = $catId;
		while($moduleName == "" || $rec->parent_id != "1"){
			$rec = $this->$modelName->getRecord($id);
			$id = $rec->parent_id;
			$moduleName = $rec->internal_name;
		}
		
		$accessLevelRecs = $this->accessLevelModel->getRecords(array("module_name"=>$moduleName."Module","category_id"=>$this->session->userdata["category_id"]));
		
		if(count($accessLevelRecs) > 0)$accessLevel = $accessLevelRecs[0];
		else $accessLevel = null;
		
		if(count($accessLevelRecs) < 1 || !$accessLevel->perm_edit){
			
			echo "0-|-".$this->lang->line("no-perm");
		
		}else{
			
			$record = $this->$modelName->getRecord($catId);
			if(is_object($record)){
				
				$order = $record->order;
				
				if($order > 0){
					
					$where = array(
						"parent_id"=>$record->parent_id,
						"order"=>$order+1
					);
					$records = $this->$modelName->getRecords($where);
					
					if(count($records) == 0){
						echo "0-|-".$this->lang->line("alreadyDown");
						
					}else{
						
						foreach($records as $r){
							if($r->order > 0){
								$newOrder = $r;
							}
						}
						
						$this->$modelName->update($record->id,array("order"=>$newOrder->order));
						$this->$modelName->update($newOrder->id,array("order"=>$order));
						
						@ob_start();
						$this->getCatsHTMLForLang($requestedModelName,$lang);
						$content = ob_get_clean();
						
						echo "1-|-".$this->lang->line("moved")."-|-".$content;
						
					}
					
				}elseif($order == 0){
					$where = array(
						"parent_id"=>$record->parent_id
					);
					$lastRecords = $this->$modelName->getRecords($where);
					foreach($lastRecords as $lastRecord){
						if($lastRecord->order > 0) $newOrder = intval($lastRecord->order) + 1;
					}
					if(!isset($newOrder)) $newOrder = 1;
					
					$this->$modelName->update($record->id,array("order"=>$newOrder));
					
					@ob_start();
					$this->getCatsHTMLForLang($requestedModelName,$lang);
					$content = ob_get_clean();
					
					echo "1-|-".$this->lang->line("moved")."-|-".$content;
				}
				
				
			}else{
				echo "0-|-".$this->lang->line("notEdited");
			}
		}
	}
}